package com.web.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.lang.reflect.Method;


/**
 * @author lenovo
 * @Description
 * @Date2025-3-18 16:48
 */
@CrossOrigin
@Aspect
@Component
public class Log4jAspect {

    //获得日志对象
    private Logger logger = Logger.getLogger(Log4jAspect.class);

    //    @Pointcut("execution(* com.web.service.impl.*ServiceImpl.*(..))")
    @Pointcut("within(com.web.service.impl.*) && @annotation(com.web.aspect.MyLog)")
    public void log(){}

    @Around("log()")
    public Object aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {
        if(logger.isDebugEnabled()){
            logger.debug("当前执行方法名为：" + joinPoint.getSignature().getName());
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            Method method = methodSignature.getMethod();
            if (method != null)
            {
                MyLog annoObj= method.getAnnotation(MyLog.class);
                logger.debug("方法的描述为：" + annoObj.value());
            }
            for(Object arg : joinPoint.getArgs()){
                logger.debug("方法的参数值：" + arg);
            }
        }
        long start = System.currentTimeMillis();
        //执行方法
        Object object = joinPoint.proceed();
        long end = System.currentTimeMillis();
        if(logger.isDebugEnabled()){
            logger.debug("方法的执行时间是：" + (end - start));
            logger.debug("方法的返回值是：" + object);
        }
        return object;
    }
}

